from . import config, cons, sqlhelper
from .log import log
from .pub import *

_POOL = None

__all__ = [
    "get_sql_client",
    "close_client",
    "try_init_db"
]


def _init_mysql():
    import pymysql
    from DBUtils.PooledDB import PooledDB
    host = config.conf.mysql.host
    port = int(config.conf.mysql.port)
    user = config.conf.mysql.user
    password = config.conf.mysql.password
    database = config.conf.mysql.database
    charset = "utf8mb4"
    # autocommit = True

    POOL = PooledDB(
        creator=pymysql,
        maxconnections=6,  # 连接池允许的最大连接数，0和None表示不限制连接数
        mincached=0,  # 初始化时，链接池中至少创建的空闲的链接，0表示不创建
        maxcached=5,  # 链接池中最多闲置的链接，0和None不限制
        blocking=True,  # 连接池中如果没有可用连接后，是否阻塞等待。True，等待；False，不等待然后报错
        maxusage=None,  # 一个链接最多被重复使用的次数，None表示无限制
        setsession=[],  # 开始会话前执行的命令列表。如：["set datestyle to ...", "set time zone ..."]
        ping=0,
        # ping MySQL服务端，检查是否服务可用。
        # 如：0 = None = never,
        # 1 = default = whenever it is requested,
        # 2 = when a cursor is created,
        # 4 = when a query is executed,
        # 7 = always
        host=host,
        port=port,
        user=user,
        password=password,
        database=database,
        charset=charset,
        # autocommit=autocommit
    )
    return POOL


def get_mysql_client():
    global _POOL
    if not _POOL:
        _POOL = _init_mysql()

    conn = _POOL.connection()
    return conn


def get_sqlit_client():
    import sqlite3
    conn = sqlite3.connect('./data/dyb.db', timeout=5)
    return conn


def get_sql_client():
    return get_sqlit_client()


def try_init_db():
    if not sqlhelper.table_exists("t_topic"):
        sql_file_path = f"{cons.res_dir_path}/schema.sql"
        sql = read_all(sql_file_path)
        sqlhelper.executescript(sql)
        log.info("init db success")


def close_client(client):
    if client is not None:
        try:
            if hasattr(client, 'close'):
                client.close()
            # client.close()
        except Exception:
            log.exception(f"unexpect close client {client} error")
